import React, { useState, useEffect, useRef } from 'react';
import { Form, Input, Button } from 'antd';
import { DeleteOutlined, EditOutlined, UpOutlined, DownOutlined } from '@ant-design/icons';
import ConditionFilterModal from '../ConditionFilterModal';
import { clone as cloneDeep } from 'ramda';
import { ElementType } from '../../config';
import { message } from 'antd';
import styled from 'styled-components';

const { TextArea } = Input;

const ConditionForm = ({ data, onUpdate, onCancel }, ref) => {
  const [form] = Form.useForm();
  const [nodeData, setNodeData] = useState(getDefaultData());
  const conditionFilterModalRef = useRef(null);


  function getDefaultData() {
    return {
      key: '',
      name: '',
      outgoings: [],
      incomings: [],
      elementType: ElementType.CONDITION,
      desc: '',
      conditions: [],
    };
  }

  useEffect(() => {
    if (data) {
      const newData = Object.assign(getDefaultData(), cloneDeep(data));
      // 确保else在最后
      const elseItemIndex = newData.conditions?.findIndex(
        (item) => item.conditionType === 'DEFAULT'
      );
      const elseItem = newData.conditions?.[elseItemIndex];
      if (elseItemIndex > -1 && elseItemIndex !== newData.conditions.length - 1) {
        newData.conditions.splice(elseItemIndex, 1);
        newData.conditions.push(elseItem);
      }
      setNodeData(newData);
    }
  }, [data]);

  const validate = () => {
    if (!nodeData.name) {
      message.error('节点名称不能为空');
      return false;
    }
    return true;
  };

  const edit = (index) => {
    conditionFilterModalRef.current.open({
      data: nodeData,
      index: index,
      afterEdit: (val) => {
        if (val) {
          if (!val.outgoing) {
            val.outgoing = data.outgoings[0];
          }
          const newConditions = [...nodeData.conditions];
          newConditions.splice(index, 1, val);
          setNodeData({ ...nodeData, conditions: newConditions });
        }
      },
    });
  };

  const sortUp = (index) => {
    if (index === 0) {
      return;
    }
    const newConditions = [...nodeData.conditions];
    const current = newConditions[index];
    newConditions.splice(index, 1);
    newConditions.splice(index - 1, 0, current);
    setNodeData({ ...nodeData, conditions: newConditions });
  };

  const sortDown = (index) => {
    if (index === nodeData.conditions.length - 1) {
      return;
    }
    const newConditions = [...nodeData.conditions];
    const current = newConditions[index];
    newConditions.splice(index, 1);
    newConditions.splice(index + 1, 0, current);
    setNodeData({ ...nodeData, conditions: newConditions });
  };

  const remove = (index) => {
    const newConditions = [...nodeData.conditions];
    newConditions.splice(index, 1);
    setNodeData({ ...nodeData, conditions: newConditions });
  };

  const addCondition = () => {
    conditionFilterModalRef.current.open({
      data: nodeData,
      afterEdit: (val) => {
        if (val) {
          if (!val.outgoing) {
            val.outgoing = data.outgoings[0];
          }
          const newConditions = [...nodeData.conditions];
          const conditionSize = newConditions.length;
          newConditions.splice(conditionSize - 1, 0, val);
          setNodeData({ ...nodeData, conditions: newConditions });
        }
      },
    });
  };

  const onSubmit = () => {
    if (!validate()) {
      return;
    }
    onUpdate(cloneDeep(nodeData));
  };

  return (
    <div className="node-condition-form">
      <Form form={form} layout="vertical">
        <Form.Item label="节点编码">
          <span>{nodeData.key}</span>
        </Form.Item>
        <Form.Item label="节点名称" required>
          <Input
            value={nodeData.name}
            onChange={(e) => setNodeData({ ...nodeData, name: e.target.value })}
            placeholder="请输入"
          />
        </Form.Item>
        <Form.Item label="节点描述">
          <TextArea
            value={nodeData.desc}
            onChange={(e) => setNodeData({ ...nodeData, desc: e.target.value })}
            placeholder="请输入"
            rows={2}
          />
        </Form.Item>
        <Form.Item label="条件表达式">
          <ConditionListStyles className="condition-list">
            {nodeData.conditions.map((item, index) => (
              <div key={index} className="condition-item">
                <div className="condition-head">
                  <div className="condition-title">{item.conditionName}</div>
                  <div className="condition-action">
                    {item.conditionType === 'CUSTOM' && (
                      <>
                        {index > 0 && (
                          <Button
                            type="link"
                            icon={<UpOutlined />}
                            onClick={() => sortUp(index)}
                            title="升序"
                          />
                        )}
                        {index < nodeData.conditions.length - 2 && (
                          <Button
                            type="link"
                            icon={<DownOutlined />}
                            onClick={() => sortDown(index)}
                            title="降序"
                          />
                        )}
                        <Button
                          type="link"
                          icon={<EditOutlined />}
                          onClick={() => edit(index)}
                          title="编辑"
                        />
                        <Button
                          type="link"
                          icon={<DeleteOutlined />}
                          onClick={() => remove(index)}
                          title="删除"
                        />
                      </>
                    )}
                  </div>
                </div>
                {item.expression && (
                  <div className="condition-body">{item.expression}</div>
                )}
              </div>
            ))}
            <div className="condition-add">
              <Button size="small" type="default" onClick={addCondition}>
                新增分支
              </Button>
            </div>
          </ConditionListStyles>
        </Form.Item>
        <Form.Item>
          <Button type="primary" onClick={onSubmit}>
            确定
          </Button>
          <Button onClick={onCancel}>取消</Button>
        </Form.Item>
      </Form>
      <ConditionFilterModal ref={conditionFilterModalRef} />
    </div>
  );
};

const ConditionListStyles = styled.div`
  &.condition-list {
    width: 100%;
    line-height: 32px;
    .condition-item {
      padding: 5px 10px;
      border: 1px solid #326394;
      border-radius: 4px;
      margin-bottom: 10px;
    }
    .condition-head {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .condition-title {
        font-size: 14px;
      }
      .condition-action {
        .el-button {
          padding: 0;
          width: 30px;
          height: 30px;
          line-height: 30px;
          border-radius: 50%;
          font-size: 14px;
        }
        .el-button + .el-button {
          margin-left: 4px;
        }
      }
    }
    .condition-body {
      border-top: 1px solid #326394;
      margin-top: 4px;
    }
    .condition-add {
      text-align: center;
    }
  }
`

export default ConditionForm; 